Java syntax
part 43/46 · 86.7 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parameterized method, type variables are written before the return type of the method in the same format as for the generic classes. In the case of constructor, type variables are declared before the constructor name.
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {
}
}
/* This method will accept only arrays of the same type as
the searched item type or its subtype*/
static <T, V extends T> boolean contains(T item, V[] arr) {
for (T currentItem : arr) {
if (item.equals(currentItem)) {
return true;
}
}
return false;
}
Generic interfaces
Interfaces can be parameterized in the similar manner as the classes.
interface Expandable<T extends Number> {
void addItem(T item);
}
// This class is parameterized
class Array<T extends Number> implements Expandable<T> {
void addItem(T item) {
}
}
// And this is not and uses an explicit type instead
class IntegerArray implements Expandable<Integer> {
void addItem(Integer item) {
}
}
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────